<?php

/**
 * Class ListNode
 */
class ListNode {
    public $val = 0;
    /** @var ListNode null  */
    public $next = null;
    function __construct($val) { $this->val = $val; }
}

class Solution {
    /**
     *
     * @param ListNode $head
     * @param Integer $val
     * @return ListNode
     */
    function removeElements($head, $val) {
        if($head === null) return null;

        while ($head !== null && $head->val === $val) {
            $head = $head->next;
        }

        $prevNode = $head;
        while ($prevNode->next !== null) {
            if ($prevNode->next->val === $val) {
                $delNode = $prevNode->next;
                $prevNode->next = $delNode->next;
                $delNode->next = null;
            } else {
                $prevNode = $prevNode->next;
            }
        }

        return $head;
    }
}
